package cn.bj.yu.forkjoin;

import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author 周宇
 * @create 2020-08-14 17:55
 * 3000 6000(ForkJoin) 9000(Stream并行流)
 */
public class ForkJoinWorkDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1(); //sum=500000000500000000 时间：14140 10215 7859 7286 7455
        //test2();  //sum=500000000500000000时间：7700 6230 5336 5517
        test3();   //sum=500000000500000000时间：957 685
    }

    //普通程序员
    public static void test1() {
        System.err.println(Instant.now());
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for (Long i = 1L; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + " 时间：" + (end - start));
    }

    //6k程序员 会使用ForkJoin
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinWork(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);//提交任务
        Long sum = submit.get();//会阻塞等待

        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + "时间：" + (end - start));
    }

    //9k程序员 并行流
    public static void test3() {
        long start = System.currentTimeMillis();
        //Stream并行流() (]
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + " 时间：" + (end - start));
    }
}